package net.maku.needy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import lombok.AllArgsConstructor;
import net.maku.framework.common.utils.PageResult;
import net.maku.framework.mybatis.service.impl.BaseServiceImpl;
import net.maku.needy.convert.NeedyMemberConvert;
import net.maku.needy.dao.NeedyMemberDao;
import net.maku.needy.dao.NeedyMemberFamilyDao;
import net.maku.needy.entity.NeedyMemberEntity;
import net.maku.needy.entity.NeedyMemberFamilyEntity;
import net.maku.needy.query.NeedyMemberQuery;
import net.maku.needy.service.NeedyMemberService;
import net.maku.needy.vo.NeedyMemberVO;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 困难职工
 *
 * @author 阿沐 babamu@126.com
 * @since 1.0.0 2025-03-19
 */
@Service
@AllArgsConstructor
public class NeedyMemberServiceImpl extends BaseServiceImpl<NeedyMemberDao, NeedyMemberEntity> implements NeedyMemberService {

    @Resource
    private NeedyMemberFamilyDao memberFamilyDao;
    @Resource
    private NeedyMemberDao memberDao;

    @Override
    public PageResult<NeedyMemberVO> page(NeedyMemberQuery query) {
        //IPage<NeedyMemberEntity> page = baseMapper.selectPage(getPage(query), getWrapper(query));
        IPage<NeedyMemberEntity> pageParams = getPage(query);
        QueryWrapper<NeedyMemberVO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(query.getRealName()),"u.real_name",query.getRealName());
        queryWrapper.eq(query.getGender() != null,"u.gender",query.getGender());
        queryWrapper.eq(StringUtils.isNotBlank(query.getOrgName()),"o.name",query.getOrgName());
        queryWrapper.orderByDesc("nm.id");
        IPage<NeedyMemberVO> page = memberDao.selectPageList(pageParams,queryWrapper);


        return new PageResult<>(page.getRecords(),page.getTotal());
    }

    private LambdaQueryWrapper<NeedyMemberEntity> getWrapper(NeedyMemberQuery query){
        LambdaQueryWrapper<NeedyMemberEntity> wrapper = Wrappers.lambdaQuery();
        return wrapper;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(NeedyMemberVO vo) {
        Long memberId = vo.getMemberId();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("member_id",memberId);
        NeedyMemberEntity needyMemberEntity = baseMapper.selectOne(queryWrapper);
        if(needyMemberEntity != null){
            throw new RuntimeException("困难职工档案已存在，请勿重复添加！");
        }
        NeedyMemberEntity entity = NeedyMemberConvert.INSTANCE.convert(vo);
        baseMapper.insert(entity);
        List<NeedyMemberFamilyEntity> memberFamilyList = vo.getMemberFamilyList();
        if(CollectionUtils.isNotEmpty(memberFamilyList)){
            memberFamilyList.forEach(m->{
                m.setMemberId(entity.getMemberId());
            });
            memberFamilyDao.insert(memberFamilyList);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(NeedyMemberVO vo) {
        NeedyMemberEntity entity = NeedyMemberConvert.INSTANCE.convert(vo);
        List<NeedyMemberFamilyEntity> memberFamilyList = vo.getMemberFamilyList();
        if(CollectionUtils.isNotEmpty(memberFamilyList)){
            setMemberId(memberFamilyList,vo.getMemberId());
            QueryWrapper<NeedyMemberFamilyEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("member_id",vo.getMemberId());
            memberFamilyDao.delete(queryWrapper);
            memberFamilyDao.insert(memberFamilyList);
        }
        updateById(entity);
    }

    private void setMemberId(List<NeedyMemberFamilyEntity> memberFamilyList,Long memberId){
        memberFamilyList.forEach(m->{
            m.setMemberId(memberId);
        });
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(List<Long> idList) {
        removeByIds(idList);
        List<NeedyMemberEntity> needyMemberEntities = memberDao.selectBatchIds(idList);
        List<Long> memberIds = needyMemberEntities.stream().map(NeedyMemberEntity::getMemberId).collect(Collectors.toList());
        QueryWrapper<NeedyMemberFamilyEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("member_id",memberIds);
        memberFamilyDao.delete(queryWrapper);
    }

}